﻿using System;
using System.Linq;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Reviewer.Entities.Services;
using Reviewer.Business;
using Reviewer.Entities;

public partial class V2Controls_Top10Video : System.Web.UI.UserControl
{
    private delegate GameVideo[] LoadVideosDelegate();
    private LoadVideosDelegate loadHandler;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Page.AddOnPreRenderCompleteAsync(
                new BeginEventHandler(this.BeginAsyncLoad),
                new EndEventHandler(this.EndAsyncLoad)
                );
        }
    }
    
    private IAsyncResult BeginAsyncLoad(object sender, EventArgs e, AsyncCallback cb, object state)
    {
        this.loadHandler = new LoadVideosDelegate(LoadVideos);
        return this.loadHandler.BeginInvoke(cb, state);
    }

    private void EndAsyncLoad(IAsyncResult ar)
    {
        this.uiRepGameVideos.DataSource = this.loadHandler.EndInvoke(ar);
        this.uiRepGameVideos.DataBind();
    }

    private GameVideo[] LoadVideos()
    {
        using (IGameService gameService = ServiceFactory.GameService)
        {
            return gameService.GetLatestVideos(10);
        }
    }

    protected void uiRepGameVideos_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            GameVideo gameVideo = e.Item.DataItem as GameVideo;
            
            HyperLink link = e.Item.FindControl("uiHlGameVideo") as HyperLink;
            Literal title = e.Item.FindControl("uiLitTitle") as Literal;
            Literal genre = e.Item.FindControl("uiLitText") as Literal;

            using (IGameService gameService = ServiceFactory.GameService)
            {
                Game currentGame = gameService.GetBy(gameVideo.GameId).FirstOrDefault();

                link.NavigateUrl = UrlUtillity.GetGameVideoUri(gameVideo);

                title.Text = (currentGame.Title.Length > 30) ? currentGame.Title.Substring(0, 30) + "..." : currentGame.Title;
                genre.Text = gameVideo.Title;
            }
        }
    }

}
